<?php

/*
 * Importa Articulos y Clientes
 */

class Importar extends Controller {
    public $lenguaje='spanish';

    function Importar() {
        parent::Controller();
        if(!$this->session->userdata('logged_in'))
            redirect('/home/');
        $this->lang->load('general',$this->lenguaje);
    }

    function index() {
        $datos['titulo_pagina'] = 'Importando';
        $this->load->view('admin/encabezado_admin.php', $datos);
        $this->load->view('admin/menu_admin.php');
        $this->load->view('admin/importar.php');
        $this->load->view('admin/pie.php');
    }

    function importar1() {
        $importar_file_articulos = $this->input->post('importar_file_articulos');
        if($importar_file_articulos) {

        // ********************** Limpiar articulos existentes **************************************************
            $this->db->query("TRUNCATE TABLE category");
            $this->db->query("TRUNCATE TABLE category_text");
            $this->db->query("TRUNCATE TABLE category_xref");
            $this->db->query("TRUNCATE TABLE product");
            $this->db->query("TRUNCATE TABLE product_price");
            $this->db->query("TRUNCATE TABLE product_category_xref");

            // ********************** Comenzar la importacion de articulos ******************************************
            // Open csv file
            $file = $_FILES["file_articulos"]["tmp_name"];
            $fp = fopen ($file,"r");
            if(!$fp) {
                $fp = fopen ($mosConfig_absolute_path."/userfiles/articulos.csv","r");
            }else {
                echo $_FILES["file_articulos"]["tmp_name"];
            }

            $i =0;
            echo "<script>document.getElementById('contador').innerHTML='Se importaron: ".$i." articulos';</script>";
            fgetcsv($fp, 8096, ';');
            while ($data = fgetcsv($fp, 8096, ';')) {
                $timestamp = time();
                // Add product information
                $q  = "INSERT INTO product (";
                $q .= "vendor_id,product_parent_id,product_publish,";
                $q .= "product_sku,";
                $q .= "product_name,";
                $q .= "product_in_stock,";

                $q .= "product_weight,";
                $q .= "product_weight_uom,";
                $q .= "product_lwh_uom,";
                $q .= "product_width,";
                $q .= "product_height,";

                $q .= "cdate,";
                $q .= "mdate) ";
                $q .= "VALUES ('1','0','Y','";
                $num = (int)$data[0];
                $q .= addslashes($num) . "','";
                $q .= addslashes($data[1]) . "','";
                $q .= addslashes($data[7]) . "','";

                $q .= addslashes($data[2]) . "','";
                $q .= addslashes($data[3]) . "','";
                $q .= addslashes($data[4]) . "','";
                $q .= addslashes($data[5]) . "','";
                $q .= addslashes($data[6]) . "','";
                $q .= "$timestamp','";
                $q .= "$timestamp');";
                $this->db->query($q);

                // Get the product ID we just created
                $product_id = $this->db->insert_id();

                // Use csv_category() method to confirm/add category tree for this product
                if($data[2]<>'') {
                    if($data[3]<>'') {
                        if($data[4]<>'') {
                            $category_id = $this->csv_category($data[2]);
                        }else {
                            $category_id = $this->csv_category($data[2]."/".$data[3]);
                        }
                    }else {
                        $category_id = $this->csv_category($data[2]);
                    }
                }

                // Insert new product/category relationships
                //		echo "category_id:";
                foreach( $category_id as $value ) {
                    $q  = "INSERT INTO product_category_xref (category_id, product_id ) VALUES (";
                    $q .= "'$value', '$product_id')";
                    $this->db->query($q);
                //		echo $value.", ";
                }
                //		echo "<br>";

                // Get default shopper group ID
                $q = "SELECT shopper_group_id FROM shopper_group ";
                $q .= "WHERE `default`='1'";
                $query = $this->db->query($q);
                $grupo = $query->row();

                $q = "DELETE FROM product_price WHERE ";
                $q .= "product_id = '$product_id'";
                $this->db->query($q);

                // for($p=1;$p<=5;$p++){
                //		echo(" csv_cant_min_$p ");
                //    if(1){
                $q = "INSERT INTO product_price ";
                $q .= "(product_price, ";
                $q .= "product_id, ";
                $q .= "product_currency, ";
                $q .= "currency_id, ";
                $q .= "shopper_group_id, ";
                $q .= "cant_min, ";
                $q .= "mdate) VALUES ('";
                $q .= str_replace(',','.',addslashes($data[8])). "','";
                $q .= $product_id . "','";
                $q .= "1','";
                $q .= "1','";
                $q .= $grupo->shopper_group_id . "','";
                $q .= "1','";
                $q .= $timestamp . "') ";
                //     }
                $this->db->query($q);
                //   }

                // Add report for this line to message
                $error  = 'Errr';
                //$error  = $dbcat->getErrorMsg();
                // $error .= $dbu->getErrorMsg();
                //$error .= $dbpp->getErrorMsg();

                $i++;
                if(($i%10)==0) {
                    echo "<script>document.getElementById('contador').innerHTML='Se importaron: ".$i." Articulos';</script>";
                //  forceFlush();
                }
            }

            fclose($fp);

            echo "<div style=\"display:inline;position:relative;float:left;width:100%; margin-left:15px;\"><lu><li>Articulos importados (total: ".$i.")</li><li><a href=".base_url()."index.php/admin/>Clic aqui para regresar al menu</a></li>";
        }// fin "if" articulos)
        $importar_file_clientes = $this->input->post('importar_file_clientes');

        if($importar_file_clientes) {
/*************************     Clientes  ********************************/
            ?><SCRIPT language=javascript>document.getElementById('importando').innerHTML='Importando Clientes: ';</SCRIPT><?


            $file = $_FILES["file_clientes"]["tmp_name"];
            $fp = fopen ($file,"r");
            if(!$fp) {
                $fp = fopen ($mosConfig_absolute_path."/userfiles/clientes.csv","r");
            }else {
                echo $_FILES["file_articulos"]["tmp_name"];
            }

            // eliminamos usuarios del ecommerce
            $sql = "DELETE FROM users WHERE usertype = 'ecommerce'";
            $this->db->query($sql);
            $i =0;
            echo "<script>document.getElementById('contador').innerHTML='Se importaron: ".$i." clientes';</script>";
            fgetcsv($fp, 8096, ';');
            while ($data = fgetcsv($fp, 18096, ';')) {
                if(isset($data[0]) and isset($data[1])) {
                    $registerDate = date( 'Y-m-d H:i:s' );

                    $username =  sprintf("%05s",$data[0]) ;
                    $name = $data[1];
                    $email = $data[7];
                    if(isset($data[14])) {
                        if($data[14]<>'') {
                            $pass = md5($data[14]);
                        }else {
                            $pass = md5("1234");
                        }
                    }else {
                        $pass = md5("1234");
                    }

                    $password = $pass;
                    $usertype = 'ecommerce';
                    $address_type = 'BT';
                    $address_1 = $data[2];
                    $activation = '1';
                    $gid = '18';
                    $phone_1 = $data[5];
                    $fax = $data[6];
                    $city = $data[3];
                    $state = $data[8];
                    $zip = $data[4];
                    $extra_field_1 = $data[9];
                    $extra_field_2 = $data[10];
                    $extra_field_3 = $data[11];
                    $extra_field_4 = $data[13];
                    $extra_field_5 = $data[12];
                    $codprv = $data[15];
                    $codtrat = $data[16];
                    $codvencom = $data[17];
                    $codcondi = $data[18];
                    $codlis = $data[19];
                    $mailv = $data[20];
                    $this->db->query("INSERT INTO users set name='".$name."',username='".$username."',password='".$pass."',usertype='".$usertype."',email='".$email."',gid='".$gid."',registerDate='".$registerDate."',activation='".$activation."',address_type='".$address_type."',phone_1='".$phone_1."',fax='".$fax."',address_1='".$address_1."',city='".$city."',state='".$state."',zip='".$zip."',extra_field_1='".$extra_field_1."',extra_field_2='".$extra_field_2."',extra_field_3='".$extra_field_3."',extra_field_4='".$extra_field_4."',extra_field_5='".$extra_field_5."',codprv='".$codprv."',codtrat='".$codtrat."',codvencom='".$codvencom."',codcondi='".$codcondi."',codlis='".$codlis."',mailv='".$mailv."'");
                    $i++;
                }
                if(($i%10)==0) {
                    echo "<script>document.getElementById('contador').innerHTML='Se importaron: ".$i." clientes';</script>";
                //   forceFlush();
                }
            }
            echo "<li>Clientes importados (total: ".$i.")</li><li><a href=".base_url()."index.php/admin/>Clic aqui para regresar al menu</a></li></lu></div>";

            fclose($fp);
        //unlink($mosConfig_absolute_path."/administrator/components/com_pshop/sincronizar/importar/PET13VEN.TXT");
    }// fin "if" clientes)
    }

    function csv_category($line) {
        $this->load->helper('text');
        // echo $line."<br>";
        // New: Get all categories in this field,
        // delimited with |
        $categories = explode("/", $line);
        $category_parent_id = '0';
        foreach( $categories as $line ) {
        // Explode slash delimited category tree into array
            $category_list = explode("/", $line);
            $category_count = count($category_list);

            // For each category in array
            for($i = 0; $i < $category_count; $i++) {
            // See if this category exists with it's parent in xref
                $q = "SELECT category.category_id FROM category, category_xref ";
                $q .= "WHERE category.category_name='" . $category_list[$i] . "' ";
                $q .= "AND category_xref.category_child_id=category.category_id ";
                $q .= "AND category_xref.category_parent_id='".$category_parent_id."'";
                //$string = ascii_to_entities( $category_list[$i]);
                //echo $string;
                //$string = $q;
                //echo "<br>".$q."<br>";
                //echo "<br>".$string."<br>";
                $query = $this->db->query($q);
                $fila = $query->row();


                // If it does not exist, create it
                if ($query->num_rows() > 0) { // Category exists
                    $category_id = $fila->category_id;
                } else { // Category does not exist - create it
                         /* $hash_secret="PHPShopIsCool";
                          $category_id = md5(uniqid($hash_secret));*/
                    $timestamp = time();

                    // Let's find out the last category in
                    // the level of the new category
                    $q = "SELECT MAX(list_order) AS list_order FROM category_xref,category ";
                    $q .= "WHERE category_parent_id='".$category_parent_id."' ";
                    $q .= "AND category_child_id=category_id ";
                    $query = $this->db->query($q);
                    $fila = $query->row();

                    $list_order = intval($fila->list_order)+1;

                    // Add category
                    $q = "INSERT INTO category ";
                    $q .= "(vendor_id,category_name, category_publish,cdate,mdate,list_order) ";
                    $q .= "VALUES ('";
                    $q .= "1', '";
                    $q .= $category_list[$i] . "', '";
                    $q .= "Y', '";
                    $q .= $timestamp . "', '";
                    $q .= $timestamp . "', '$list_order')";
                    $query = $this->db->query($q);
                    //					  echo "last ID: ".$category_id."<br>";

                    // Get the product ID we just created
                    $category_id = $this->db->insert_id();

                    // Create xref with parent
                    $q = "INSERT INTO category_xref ";
                    $q .= "(category_parent_id, category_child_id) ";
                    $q .= "VALUES ('";
                    $q .= $category_parent_id . "', '";
                    $q .= $category_id . "')";
                    $query = $this->db->query($q);
                }
                // Set this category as parent of next in line
                $category_parent_id = $category_id;
            //			  echo "p:". $category_parent_id.", ";
            } // end for
        }
        $category[] = $category_id;
        //		 echo "id:". $category_parent_id."<br><br><br>";
        // Return an array with the last category_ids which is where the product goes
        return $category;

    } // End function csv_category



    function editar() {
        $id = $this->uri->segment(4);
        $datos['titulo_pagina'] = 'Noticias';
        $this->load->view('admin/encabezado_admin.php', $datos);
        $this->load->view('admin/menu_admin.php');
        $consulta['query'] = $this->db->query("SELECT * FROM noticias WHERE id=".$id);
        $fila = $consulta['query']->row();

        $this->load->library('fckeditor','num1');
        $this->fckeditor->BasePath = base_url().'system/plugins/fckeditor/';
        $this->fckeditor->ToolbarSet = 'Default';
        $this->fckeditor->Height = '500';
        $this->fckeditor->Value=$fila->texto;
        $consulta['fck1'] = $this->fckeditor->CreateHtml();

        $this->fckeditor->InstanceName = 'num2';
        $this->fckeditor->Value=$fila->texto_ampliado;
        $consulta['fck2'] = $this->fckeditor->CreateHtml();

        $this->load->view('admin/am_noticia.php',$consulta);
        $this->load->view('pie.php');
    }

    function guardar() {
        $id = $this->input->post('id');
        $fecha = $this->input->post('fecha');
        $texto = $this->input->post('num1');
        $texto_ampliado = $this->input->post('num2');
        $nombre = $this->input->post('nombre');
        $peso = $this->input->post('peso');
        $tipo = $this->input->post('tipo');

        if($this->db->simple_query("SELECT * FROM eventos WHERE id=".$id)) {
            $query = $this->db->query("UPDATE eventos set nombre='".$nombre."', texto='".$texto."', texto_ampliado='".$texto_ampliado."', fecha='".$fecha."', tipo='".$tipo."' WHERE id=".$id);
        }else {
            $query = $this->db->query("INSERT INTO eventos set nombre='".$nombre."', texto='".$texto."', texto_ampliado='".$texto_ampliado."', fecha='".$fecha."', tipo='".$tipo."'");
        }
        redirect('/admin/eventos');
    }

    function eliminar() {
        $id = $this->uri->segment(4);
        $query = $this->db->query("DELETE from eventos WHERE id=".$id);
        redirect('/admin/eventos');
    }

}
?>